/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package meteocal.business.control;

import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.inject.Inject;
import meteocal.business.entity.Weather;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author luana
 */
public class WeatherChecker {
    
   
    private static final String RESOURCE_URL =  "http://api.openweathermap.org/data/2.5/forecast" ; 
    private static final String APPID = "&APPID=" ;
    private static final String APIKEY = "756e4a24cdee61363adc6d6c9c29d975"; 
    private static final String QUERY_TYPE = "?q=";
    
    private static final Logger logger = Logger.getLogger(WeatherChecker.class.getName());
    
    private DateUtils du; 
    
    
    public WeatherChecker(){
        du = new DateUtils();
    }
    /**
     * Given the place and time of the event, it returns the expected forecast. 
     * It is avaialble every three hours, up to 5 days from the current day. 
     * For the structure of the json object given by the external resource, see
     * http://openweathermap.org/weather-data#5days
     * @param city
     * @param day
     * @param time
     * @return The expected weather for the given time and place.
     */
    public Weather checkWeather(String city, Date day, Date time){
        
        String uri = RESOURCE_URL + QUERY_TYPE + city + APPID + APIKEY ;
              
        Client client = ClientBuilder.newClient();
        
        WebTarget target = client.target(uri);
        
        Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON);
        
        Response response = invocationBuilder.get();
        
        
        if (response.getStatus() != 200){
           logger.log(Level.INFO, "Forecast Service not avaiable");
           return new Weather (1, "n/d", "None", "url");
        }
        
                
        
        String jsonContent = response.readEntity(String.class);
        
                
        
        try {
            JSONObject jsonObject = new JSONObject(jsonContent);
            if(jsonObject.has("cod")){
                if(jsonObject.getInt("cod")==404){
                    logger.log(Level.INFO, "City not found");
                    return new Weather (1, "n/d", "None", "url");
                } 
            }
            
            JSONArray list = jsonObject.getJSONArray("list");
            JSONObject entry = new JSONObject();
            
            int i = 0;
            String dt_text = "";
            String dateTest = du.convertDateToString(day)+" "+du.convertTimeToString(time);
            
            
    
            while(!dt_text.equals(dateTest)){
                 if(i==list.length()){
                     return new Weather (1, "n/d", "None", "url");
                 } else {
                    entry = list.getJSONObject(i);
                    dt_text = entry.getString("dt_txt");
                    i++;  
                 }
                
            }
            
            JSONArray JSONArray_weather = entry.getJSONArray("weather");
            
           
            
            JSONObject JSONObject_weather = JSONArray_weather.getJSONObject(0);
           
            int result_id = JSONObject_weather.getInt("id");
            String result_description = JSONObject_weather.getString("description");
            String result_main = JSONObject_weather.getString("main");
            String result_icon = JSONObject_weather.getString("icon");
            
            
            logger.log(Level.INFO, "Forecast found");
            return new Weather (result_id, result_description, result_main, result_icon);
            
        } catch (JSONException ex) {
            Logger.getLogger(WeatherChecker.class.getName()).log(Level.SEVERE, null, ex);
            return new Weather (1, "n/d", "None", "url");
        }
        
        
        
    }
    
}
